#!/usr/bin/env python3
"""
HEMC Validation CLI - Configuration Driven Approach
"""

import json
from pathlib import Path

import click
from icecream import ic

from pyauto.config.models import HEMCConfig
from pyauto.config.router import router

# Add src to path to allow imports
# sys.path.insert(0, str(Path(__file__).parent / "src"))

if False:
    _cwd = Path(__file__).parent
    _prjroot = _cwd.parent  ## git repo 根目录
    _g4cxxdir = _prjroot / 'G4'  ## g4 cxx 项目根目录
    _g4cxxdir = _g4cxxdir.resolve()
    _outdir = _cwd / 'post'  # 后处理分析
    _outdir = _outdir.resolve()

    ic(_g4cxxdir)
    ic(_outdir)


@click.command(help='HEMC post-processing toolkit.')
## argument 是 命令行必填参数
## @click.argument('json_config_path', type=click.Path(exists=True))
## option 是 命令行可选参数
@click.option(
    '-c',
    '--config',
    'json_config_path',
    type=click.Path(exists=False),  # 允许默认文件不存在
    default=Path.cwd() / 'config.json',
    show_default=True,
    help='JSON 配置文件路径',
)
def main(json_config_path):
    """JSON_CONFIG_PATH: path to the configuration file."""
    ## read from json config files
    json_p = Path(json_config_path).expanduser().resolve()
    json_in = json.loads(json_p.read_text())
    click.echo(f'Config loaded: {json_in}')
    config = HEMCConfig.model_validate(json_in)

    try:
        ## 根据 json 中的配置，发送到不同的函数执行
        return router.dispatch(config)
    except json.JSONDecodeError as e:
        print(f"Error parsing JSON: {e}")
        return
    except ValueError as e:
        print(f"Value error: {e}")
        return
    except Exception as e:
        print(f"Error executing command: {e}")
        import traceback

        traceback.print_exc()
        return


if __name__ == "__main__":
    main()
